<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of login
 *
 * @author pudy
 */
class Login extends CI_Controller {

    public function index() {
        $data['title'] = 'Login Page';
        $data['main_content'] = 'login/login_view';
        $fl = $this->session->flashdata('message');
        if ($fl != '')
            $data['message'] = $fl;

        $this->load->view('includes/template', $data);
    }

    function submit() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        //$password = md5($this->input->post('password'));

        $this->load->model('userModel', 'userModel');

        $options = array('username' => $username, 'password' => $password);
        $getReturn = $this->userModel->getUsers($options);
        if (is_bool($getReturn) && !$getReturn) {
            //Login gagal, gak ada user yang memenuhi
            $message = 'Username and password do not match.';
            $this->session->set_flashdata('message', $message);
            redirect('/login', 'refresh');
        } else {
            //Authenticate success
            //Cek, kali aja ada yang 1 imel buat banyak akun:
            if (count($getReturn) == 1) {
                //Sign In OK
                $session_data = array(
                    'user_id' => $getReturn[0]->id,
                    'name' => $getReturn[0]->name,
                    'username' => $getReturn[0]->username
                );
                $this->session->set_userdata($session_data);
                /*echo $getReturn[0]->id;
                echo br(1);
                echo $getReturn[0]->name;
                echo br(1);
                echo $getReturn[0]->username;
                echo br(1);*/
                redirect('/home', 'refresh');
            } else {
                //Sign In Not OK, ada 1 imel yang daftarin lebih dari 1 akun
                show_error('More than 1 user with the same email.');
            }
        }
    }

    function logout() {
        $session_data = array(
            'user_id' => '',
            'name' => '',
            'username' => ''
        );
        $this->session->unset_userdata($session_data);

        $message = 'You have logged out.';
        $this->session->set_flashdata('message', $message);
        redirect('/welcome', 'refresh');
    }

}

?>
